<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/10
 * Time: 16:40
 */

namespace Admin\Controller;

use Admin\Controller\AdminController;
use Admin\Model\AppointmentModel;
use Admin\Model\BespeakModel;
use Admin\Model\OrganizationModel;
use Admin\Model\UserModel;
use Common\Lib\Util\LogUtil;
use Org\Util\String;

/**
 * @#todo 预约挂号模块
 * @menu 预约挂号管理
 * @author fanyuliang
 * @menuAuto index
 * @order 270
 * @icon article.png
 */
class AppointmentController extends AdminController {

    private $orgModel;
    private $userModel;
    private $bespeakModel;
    private $appointmentModel;

    function __construct() {
        parent::__construct();
        $this->orgModel = new OrganizationModel();
        $this->userModel = new UserModel();
        $this->bespeakModel = new BespeakModel();
        $this->appointmentModel = new AppointmentModel();
        $orgList = $this->orgModel->order('convert(name using gbk) asc')->select();
        $this->assign('orgList',$orgList);
        $this->assign('orderTimeRange',C('ORDER_TIME_RANGE'));
        $this->assign('curDayWeek',date('Y-m-d'));
    }

    /**
     * @todo 预约分配列表
     * @menu 预约分配列表
     * @order 1
     */
    public function index() {
        $this->setForm();
        $this->assign('curDate',date('Y-m-d'));
        $this->display();
    }

    /**
     *
     * @todo 用户预约列表
     * @menu 用户预约列表
     * @order 2
     */
    public function bespeak() {
        $where = array();
        if ($this->userInfo['role_id'] == C('EMPLOYEE_ROLE_ID')) {
            $where['user_id'] = session('userId');
        }
        $pageSize = 15;
        $order = 'status desc,order_time desc,create_time desc';
        $data = $this->bespeakModel->getList($where,$pageSize,$order);
        $bespeakList = $data['list'];
        $this->assign('bespeakList',$bespeakList);
        $this->assign('page',$data['page']);
        $this->assign('nowPage',$data['nowPage']);
        $this->assign('pageSize',$pageSize);
        $this->display();
    }

    /**
     * @todo 设置预约
     */
    public function add() {
        if (IS_POST) {
            $this->doSave();
        }
        $id = I('id');
        $appDetail = $this->appointmentModel->where(array('id' => $id))->find();
        if ($appDetail) {
            $appDetail['time_range'] = json_decode($appDetail['time_range'],true);
        } else {
            $appDetail['order_time'] = time();
        }
        $this->assign('orderTimeRange',C('ORDER_TIME_RANGE'));
        $this->assign('appDetail',$appDetail);
        $token = String::keyGen();
        session('orderFormToken',$token);
        $this->assign('formToken',$token);
        $this->display();
    }

    protected function doSave() {
        $response = array('status' => false, 'msg' => '预约信息保存失败!');
        $token = $_POST['token'];
        if (!session('orderFormToken') || strcasecmp(session('orderFormToken'),$token) != 0) {
            $response['msg'] = '请勿重复提交';
            $this->ajaxReturn($response);
        }
        $rs = $this->appointmentModel->add($_POST);
        if ($rs !== false) {
            session('orderFormToken',null);
            $response['status'] = true;
            $response['msg'] = '预约信息保存成功!';
        }
        $this->ajaxReturn($response);
    }

    public function getUserByOrgId() {
        $orgId = I('orgId');
        $users = $this->userModel->getUserByOrgId($orgId);
        $this->ajaxReturn($users);
    }

    //获取当前日期下的所有服务人员
    public function getUserList() {
        $curTime = I('curTime');
        $userList = $this->appointmentModel->getList($curTime);
        $reservedNums = $this->bespeakModel->getReservedNumsByUser($curTime);
        $timeRange = $userList[$curTime];
        foreach ($timeRange as $time => $items) {
            foreach ($items as $orgId => $item) {
                foreach ($item as $key => $app) {
                    $app['surplus'] = 0;
                    foreach ($reservedNums as $reserved) {
                        if ($reserved['org_id'] == $orgId && $reserved['user_id'] == $app['user']['id'] && $reserved['time_range'] == $time) {
                            $app['surplus'] = $reserved['surplus'];
                            break;
                        }
                    }
                    $userList[$curTime][$time][$orgId][$key] = $app;
                }
            }
        }
        $this->assign('userList',$userList);
        $this->assign('defaultDate',$curTime);
        $this->display('user_list');
    }

    /**
     * @todo 删除预约
     */
    public function delApp() {
        $response = array('status' => false, 'msg' => '预约信息删除失败!');
        $id = $_POST['id'];
        $time = $_POST['time'];
        if (!$id) {
            $response['msg'] = '无效的参数!';
            $this->ajaxReturn($response);
        }
        $rs = $this->appointmentModel->del($id,$time);
        if ($rs !== false) {
            $response['status'] = true;
            $response['msg'] = '预约信息删除成功!';
        }
        $this->ajaxReturn($response);
    }

    // 周切换
    public function getWeekList() {
        // 0 当前周 1 上一周 2 下一周
        $type = I('type',0);
        $curTime = I('curTime');
        switch ($type) {
            case 0:
                $curWeek = getCurWeek();
                break;
            case 1:
                $curWeek = getPrevWeek($curTime);
                break;
            case 2:
                $curWeek = getNextWeek($curTime);
                break;
        }
        $weekList = getWeekRange($curWeek['start'],$curWeek['end']);
        $this->assign('weekList',$weekList);
        $this->assign('startDate',$curWeek['start']);
        //处理周选项卡中默认日期
        $defaultDate = date('Y-m-d');
        if ($type > 0) {
            $flag = false;
            foreach ($weekList as $week) {
                if ($week['fullDay'] == $defaultDate) {
                    $flag = true;
                    break;
                }
            }
            if (!$flag) {
                $defaultDate = $curWeek['start'];
            }
        }
        $this->assign('defaultDate',$defaultDate);
        $this->display('week');
    }

    /**
     * @todo 取消预约
     */
    public function cancelBespeak() {
        $response = array('status' => false, 'msg' => '预约信息取消失败!');
        $id = I('id');
        if (!$id) {
            $response['msg'] = '无效的参数';
            $this->ajaxReturn($response);
        }
        $row = $this->bespeakModel->where(array('id' => $id))->find();
        $orderDate = date('Y-m-d H:i:s',$row['order_time']);
        $timeRange = $row['time_range'];
        $rangeStart = sprintf('%s:00',substr($timeRange,0,5));
        $rangeEnd = sprintf('%s:00',substr($timeRange,8));
        $orderStart = strtotime(str_replace('00:00:00',$rangeStart,$orderDate));
        $orderEnd = strtotime(str_replace('00:00:00',$rangeEnd,$orderDate));

        if ($orderEnd < time()) {
            $response['msg'] = '预约已过期，无法取消!';
            $this->ajaxReturn($response);
        } else {
            $minute = floor(($orderStart - time())/60);
            if ($minute < 30) {
                $response['msg'] = '预约开始前的30分钟，无法取消!';
                $this->ajaxReturn($response);
            }
        }

        $rs = $this->bespeakModel->where(array('id' => $id))->save(array('status' => 0));
        if ($rs !== false) {
            $row = $this->bespeakModel->relation(array('user'))->where(array('id' => $id))->find();
            $templateId = C('WEIXIN_TEMPLATE_BESPEAK_CANCEL');
            $title = '预约取消通知！';
            $option = array(
                'first' => array('value' =>'预约已取消','color' => '#ff0000'),
                //预约号
                'keyword1' => array('value' => date('YmdHis',$row['create_time']),'color' => '#173177'),
                //预约时间
                'keyword2' => array('value' => sprintf('%s（%s）',date('Y年m月d日',$row['order_time']),$row['time_range']),'color' => '#173177'),
                //备注
                'remark' => array('value' => sprintf('%s %s的预约已成功取消，操作人：%s',date('Y年m月d日',$row['order_time']),$row['time_range'],$this->userInfo['real_name']),'color' => '#ff0000')
            );
            $openId = $this->userModel->where(array('id' => $row['member_id']))->getField('openid');
            $options = array(
                'templateId' => $templateId,
                'bespeakId' => $id,
                'openId' => $openId,
                'userType' => '普通用户',
                'data' => $option,
                'title' => $title
            );
            //发送给预约人员
            $this->sendNotice($options);

            //发送给工作人员
            $openId = $this->userModel->where(array('id' => $row['user_id']))->getField('openid');
            if ($openId) {
                $options['openId'] = $openId;
                $options['userType'] = '工作人员';
                $this->sendNotice($options);
            }
            $response['status'] = true;
            $response['msg'] = '预约信息取消成功!';
            $this->ajaxReturn($response);
        }
        $this->ajaxReturn($response);
    }

    //发送预约通知
    private function sendNotice($options) {
        $option = array(
            //接收者openid
            'touser' => $options['openId'],
            //模板ID
            'template_id' => $options['templateId'],
            //模板跳转链接，不填则不用跳转
            'url' => '',
            //模板数据
            'data' => $options['data']
        );
        $response = sendWenXinNotice($option);
        $result = $response['result'];
        LogUtil::info(sprintf('%s接收方用户类型：%s',$options['title'],$options['userType']));
        if (is_array($result)) {
            $result['bespeakId'] = $options['bespeakId'];
            $result['toUser'] = $options['openId'];
            $result['userType'] = $options['userType'];
            LogUtil::info($result);
        } else {
            LogUtil::info(sprintf('预约id : %s , openId : %s , 用户类型 : %s , 信息 : %s', $options['bespeakId'], $options['openId'], $options['userType'], $response['weObj']->errMsg));
        }
        return $result;
    }

}